<script setup lang="ts">
import { onMounted, ref, nextTick, reactive, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import commonSearch from "./commonSearch.vue";
import JsonViewer from "@/components/jsonVewer/index.vue";
import { getAssetList, deleteAsset, deleteTag, addTag } from "../servers";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps<{
  task: string;
}>();
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const assetList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);

// 标签编辑相关状态
const editingRowId = ref(null);
const newTagValue = ref("");
const tagInputRef = ref();

const columns = ref<TableColumn[]>([
  {
    label: "名称",
    prop: "name",
    show: true,
    width: 120,
  },
  {
    label: "分类",
    prop: "category",
    show: true,
    width: 120,
  },
  {
    label: "描述",
    prop: "description",
    show: true,
    width: 220,
  },
  {
    label: "公司",
    prop: "company",
    show: true,
    width: 140,
  },
  {
    label: "项目",
    prop: "project",
    show: true,
  },
  {
    label: "TAG",
    prop: "tags",
    minWidth: 120,
    show: true,
    slot: "tags",
  },
  {
    label: "时间",
    prop: "time",
    width: 180,
    show: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 120,
    show: true,
    slot: "action",
    fixed: "right",
  },
]);

const formData = ref({
  search: "",
});

// 处理查看详情
const handleViewDetail = (row: any) => {
  console.log("查看详情:", row);
  dialogVisible.value = false;

  // 模拟完整的资产数据
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定删除该条数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteAsset({ ids: [row.id], index: "mp" });
    ElMessage.success("删除成功");
    getPageData();
  });
};

const getPageData = async () => {
  const params: any = {
    ...formData.value,
    pageIndex: pagination.currentPage,
    pageSize: pagination.pageSize,
  };
  if (props.task) {
    params.filter = {
      task: [props.task],
    };
  }
  const { data } = await getAssetList({ data: params, type: "mp" });
  assetList.value = data.list;
  pagination.total = data.total;
};

onMounted(() => {
  getPageData();
});

const handleSearch = (v: any) => {
  // console.log(v, "formData");
  getPageData();
};

const handleSearchReset = () => {
  console.log("reset");
  // 重置表单数据
  formData.value = {
    search: "",
  };
  pagination.currentPage = 1;
  getPageData();
};

// 点击添加标签按钮
const handleAddTag = async (row: any) => {
  console.log("添加标签:", row);
  editingRowId.value = row.id;
  newTagValue.value = "";

  // 等待DOM更新后聚焦输入框
  await nextTick();
  if (tagInputRef.value) {
    tagInputRef.value.focus();
  }
};

// 输入框失去焦点时触发
const handleTagBlur = async (row: any) => {
  const trimmedValue = newTagValue.value.trim();

  if (trimmedValue) {
    // 确保row.tags是数组
    if (!row.tags) {
      row.tags = [];
    }

    // 检查标签是否已存在
    if (!row.tags.includes(trimmedValue)) {
      // row.tags.push(trimmedValue);
      // console.log("添加标签成功:", trimmedValue, "到行:", row);
      try {
        await addTag({ id: row.id, tp: "mp", tag: trimmedValue });
        ElMessage.success("添加标签成功");
        getPageData();
      } catch (error) {
        ElMessage.error("添加标签失败");
      }
    } else {
      console.log("标签已存在:", trimmedValue);
    }
  }

  // 重置编辑状态
  editingRowId.value = null;
  newTagValue.value = "";
};

// 按下回车键时也触发添加
const handleTagKeydown = (event: Event, row: any) => {
  const keyboardEvent = event as KeyboardEvent;
  if (keyboardEvent.key === "Enter") {
    handleTagBlur(row);
  } else if (keyboardEvent.key === "Escape") {
    // 按ESC键取消编辑
    editingRowId.value = null;
    newTagValue.value = "";
  }
};

const handleDeleteTag = async (row: any, tag: string) => {
  console.log("删除标签:", row, tag);
  try {
    await deleteTag({ id: row.id, tp: "mp", tag: tag });
    ElMessage.success("删除标签成功");
    getPageData();
  } catch (error) {
    ElMessage.error("删除标签失败");
  }
};

const handlePaginationChange = (page: number) => {
  pagination.currentPage = page;
  getPageData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  getPageData();
};
</script>

<template>
  <commonSearch
    v-model="formData"
    @search="handleSearch"
    @reset="handleSearchReset"
  />
  <div style="height: 10px"></div>
  <el-card>
    <DynamicTable
      :pagination="pagination"
      :columns="columns"
      :data="assetList"
      :loading="loading"
      @current-page-change="handlePaginationChange"
      @size-change="handleSizeChange"
    >
      <template #action="{ row }">
        <el-button type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
      </template>
      <template #tags="{ row }">
        <el-tag
          v-for="tag in row.tags"
          @close="handleDeleteTag(row, tag)"
          closable
          :key="tag"
          type="success"
        >
          {{ tag }}
        </el-tag>

        <!-- 编辑状态：显示输入框 -->
        <el-input
          v-if="editingRowId === row.id"
          ref="tagInputRef"
          v-model="newTagValue"
          size="small"
          placeholder="输入标签名称"
          style="width: 120px; margin-left: 4px"
          @blur="handleTagBlur(row)"
          @keydown="handleTagKeydown($event, row)"
        />

        <!-- 非编辑状态：显示添加按钮 -->
        <el-button
          v-else
          type="default"
          size="small"
          @click="handleAddTag(row)"
          style="margin-left: 4px"
        >
          + addTag
        </el-button>
      </template>
    </DynamicTable>
  </el-card>
</template>

<style scoped lang="scss">
// 标签样式
:deep(.el-tag) {
  margin-right: 4px;
  margin-bottom: 2px;
}

// 标签输入框样式
:deep(.el-input.is-small .el-input__inner) {
  height: 24px;
}
</style>
